from PyQt5.QtCore import pyqtProperty, pyqtSignal, pyqtSlot, QRectF, Qt, QUrl, QObject, QTimer
from PyQt5.QtGui import QColor, QGuiApplication, QPainter, QPen
from PyQt5.QtQml import qmlRegisterType
from PyQt5.QtQuick import QQuickPaintedItem, QQuickView

import gym


class MyClass(QObject):
    @pyqtSlot(str)  # 输入参数类型为str
    def outputString(self, string):
        print(string)

    @pyqtSlot(str, result=str)  # 声明为槽，输入参数为int类型，返回值为str类型
    def returnValue(self, value):
        return str(value + "sdafdswf")


class PieChart(QQuickPaintedItem):
    chartCleared = pyqtSignal()  # 定义信号

    @pyqtProperty(str)
    def name(self):
        return self._name

    @name.setter
    def name(self, name):
        self._name = name

    @pyqtProperty(QColor)
    def color(self):
        return self._color

    @color.setter
    def color(self, color):
        self._color = QColor(color)

    def __init__(self, parent=None):
        super(PieChart, self).__init__(parent)

        self._name = ""
        self._color = QColor()

    def paint(self, painter):
        painter.setPen(QPen(self._color, 2))
        painter.setRenderHints(QPainter.Antialiasing, True)

        rect = QRectF(0, 0, self.width(), self.height()).adjusted(1, 1, -1, -1)
        painter.drawPie(rect, 90 * 16, 290 * 16)

    @pyqtSlot()
    def clearChart(self):
        self.color = QColor(Qt.transparent)
        self.update()

        self.chartCleared.emit()


def outputstring(str):
    print(str)

    # barcode
    # @pyqtProperty(str, notify=barcodeChanged)
    # def barcode(self):
    #     return self._barcode
    #
    # @barcode.setter
    # def barcode(self, value):
    #     self._barcode = value
    #     self.barcodeChanged.emit(value)


if __name__ == '__main__':
    env = gym.make("LunarLander-v2")


    path = 'qml/main.qml'
    app = QGuiApplication([])
    view = QQuickView()
    vm = MyClass()
    context = view.rootContext()
    context.setContextProperty("vm", vm)

    qmlRegisterType(PieChart, "Charts", 1, 0, "PieChart")

    view.setResizeMode(QQuickView.SizeRootObjectToView)
    view.engine().quit.connect(app.quit)
    view.setSource(QUrl(path))
    view.show()

    rootobj = view.rootObject() # 这块要放后边
    rootobj.sendClicked.connect(outputstring)  # 连接QML信号sendClicked

    timer = QTimer()
    timer.start(2000)
    timer.timeout.connect(rootobj.updateRotater)  # 调用QML函

    import os
    import sys

    # app = QGuiApplication(sys.argv)
    # qmlRegisterType(PieChart, "Charts", 1, 0, "PieChart")
    # view = QQuickView()
    # view.setResizeMode(QQuickView.SizeRootObjectToView)
    # view.setSource(
    #     QUrl.fromLocalFile(
    #         os.path.join(os.path.dirname(__file__), "test.qml")))
    # view.show()

    sys.exit(app.exec_())

    # app.exec_()